package com.sljy.hzk.ui;

import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.TextView;
import android.widget.Toast;

import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import com.sljy.hzk.R;
import com.sljy.hzk.annotation.ActivityInfo;
import com.sljy.hzk.base.BaseActivity;
import com.sljy.hzk.net.CommonResult;
import com.sljy.hzk.net.HttpHeper;
import com.sljy.hzk.net.service.TaskService;
import com.sljy.hzk.view.WaveView;

import java.util.Arrays;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 自定义二维码扫描页面 和 nfc感应
 */
@ActivityInfo(layout = R.layout.activity_nfc, isShowActionBar = true, title = "任务解锁")
public class NfcActivity extends BaseActivity {
    private CaptureManager capture;
    private DecoratedBarcodeView barcodeScannerView;
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    @BindView(R.id.qr_text)
    TextView mNfcText;
    private String mTagText;
    private WaveView mWaveView;

    @Override
    protected void init() {
        InitNfc();
    }

    /**
     * 初始化Nfc
     * */
    private void InitNfc(){
        mWaveView = (WaveView) findViewById(R.id.wave_view);
        mWaveView.setDuration(3000);
        mWaveView.setStyle(Paint.Style.FILL);
        mWaveView.setSpeed(300);
        mWaveView.setColor(Color.parseColor("#00FFFF"));
        mWaveView.setInterpolator(new AccelerateInterpolator(1.2f));
        mWaveView.start();

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mAdapter == null) {
            Toast.makeText(this, "设备不支持NFC！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!mAdapter.isEnabled()) {
            Toast.makeText(this, "请在系统设置中先启用NFC功能！", Toast.LENGTH_SHORT).show();
            return;
        }
        //创建intent检测nfc
        mPendingIntent = PendingIntent
                .getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    }

    @Override
    public void onNewIntent(Intent intent) {
       // super.onNewIntent(intent);
        //我们接受到消息啦，可以处理了
        //1.获取Tag对象
        Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        //2.获取Ndef的实例
        Ndef ndef = Ndef.get(detectedTag);
        mTagText = ndef.getType() + "\nmaxsize:" + ndef.getMaxSize() + "bytes\n\n";
        readNfcTag(intent);
        mNfcText.setText(mTagText);
        //请求解锁
        DoUnLock(mTagText);
    }

    private void DoUnLock(String mTagText){
        Intent intent = getIntent();
        int DoId = intent.getIntExtra("workId",10);
        String date = intent.getStringExtra("date");
        HttpHeper.get().create(TaskService.class)
                .UnlockTask(Integer.parseInt(mTagText), DoId, date)
                .enqueue( new Callback<CommonResult<String>>(){
                    @Override
                    public void onResponse(Call<CommonResult<String>> call, Response<CommonResult<String>> response) {
                        if(response.body().getData().equals("1")){
                            showToast(response.body().getMsg());
                        }else{
                            showToast(response.body().getMsg());
                            return;
                        }
                        //如果是点击执行的话，应该直接进入到界面
                        //把本地的缓存修改为解锁

                    }
                    @Override
                    public void onFailure(Call<CommonResult<String>> call, Throwable t) {
                        showToast("解锁失败");
                    }
                });

    }


    private void readNfcTag(Intent intent) {
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                    NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage msgs[] = null;
            int contentSize = 0;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                    contentSize += msgs[i].toByteArray().length;
                }
            }
            try {
                if (msgs != null) {
                    NdefRecord record = msgs[0].getRecords()[0];
                    String textRecord = parseTextRecord(record);
                    mTagText += textRecord + "\n\ntext\n" + contentSize + " bytes";
                }
            } catch (Exception e) {
            }
        }
    }

    /**
     * 解析NDEF文本数据，从第三个字节开始，后面的文本数据
     *
     * @param ndefRecord
     * @return
     */
    public static String parseTextRecord(NdefRecord ndefRecord) {
        /**
         * 判断数据是否为NDEF格式
         */
        //判断TNF
        if (ndefRecord.getTnf() != NdefRecord.TNF_WELL_KNOWN) {
            return null;
        }
        //判断可变的长度的类型
        if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
            return null;
        }
        try {
            //获得字节数组，然后进行分析
            byte[] payload = ndefRecord.getPayload();
            //下面开始NDEF文本数据第一个字节，状态字节
            //判断文本是基于UTF-8还是UTF-16的，取第一个字节"位与"上16进制的80，16进制的80也就是最高位是1，
            //其他位都是0，所以进行"位与"运算后就会保留最高位
            String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8" : "UTF-16";
            //3f最高两位是0，第六位是1，所以进行"位与"运算后获得第六位
            int languageCodeLength = payload[0] & 0x3f;
            //下面开始NDEF文本数据第二个字节，语言编码
            //获得语言编码
            String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
            //下面开始NDEF文本数据后面的字节，解析出文本
            String textRecord = new String(payload, languageCodeLength + 1,
                    payload.length - languageCodeLength - 1, textEncoding);
            return textRecord;
        } catch (Exception e) {
            throw new IllegalArgumentException();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (this.mAdapter == null)
            return;
        if (!this.mAdapter.isEnabled()) {
            Toast.makeText(this, "请在系统设置中先启用NFC功能！", Toast.LENGTH_SHORT).show();
        }
        //开启监听nfc设备
        this.mAdapter.enableForegroundDispatch(this, this.mPendingIntent, null, null);
      //  capture.onResume();
    }



    @Override
    protected void onPause() {
        super.onPause();
        if (mAdapter != null) {
            Log.i("QrCodeActivity", "onPause: 关闭监听nfc设备");
            mAdapter.disableForegroundDispatch(this);
        }
        //capture.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //capture.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //capture.onSaveInstanceState(outState);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
       // capture.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
